package cn.jinjimi.app.custom.ui.fragment;

import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import cn.jinjimi.base.Task.TaskExecutor;
import cn.jinjimi.base.util.ToastUtils;
import cn.jinjimi.framework.helper.annotation.EventTrace;
import cn.jinjimi.framework.helper.annotation.EventTraceSelector;
import cn.jinjimi.app.R;
import cn.jinjimi.app.bean.EventID;
import cn.jinjimi.app.custom.entity.Custom;
import cn.jinjimi.app.custom.iview.CustomerListView;
import cn.jinjimi.app.custom.manager.CustomsManager;
import cn.jinjimi.app.custom.ui.activity.CustomArchivesActivity;
import cn.jinjimi.app.custom.ui.activity.CustomSearchActivity;
import cn.jinjimi.app.custom.ui.adapter.CustomerAllAdapter;
import cn.jinjimi.app.custom.ui.view.CustomAllHeadView;
import cn.jinjimi.app.presenter.CustomerAllPresenter;
import cn.jinjimi.app.main.dialog.CommMenuDialog;
import cn.jinjimi.app.main.extend.BaseFragment;
import cn.jinjimi.app.main.widget.SideBar;
import cn.jinjimi.app.main.widget.XListView.XListView;

import java.util.ArrayList;
import java.util.List;

/**
 * 客户--全部客户
 * <p/>
 * Created by jinsen on 15/10/21.
 */
public class CustomerAllFragment extends BaseFragment implements CustomerListView
        , XListView.IXListViewListener, CustomerAllAdapter.onActionClickListener
        , SideBar.OnTouchingLetterChangedListener, View.OnClickListener {

    RelativeLayout mRootView;
    XListView mListView;
    SideBar mSidebar;
    LinearLayout mCustomerSearchView;

    CustomerAllAdapter mAdapter;

    CustomerAllPresenter mPresenter;
    View mLoadingView;
    View emptyView;

    CustomAllHeadView mCustomAllHeadView;
    TextView mIndexFlagTv;

    @Override
    protected int getLayoutResourceId() {
        return R.layout.fragment_all_customer_layout;
    }

    @Override
    protected void initial() {
        initView();
        initListener();
        initData();
    }

    protected void initView() {
        mRootView = (RelativeLayout) findView().findViewById(R.id.root_view);
        mListView = (XListView) findView().findViewById(R.id.all_customer_listview);
        mCustomerSearchView = (LinearLayout) findView().findViewById(R.id.customer_header_search);
        mCustomerSearchView.setVisibility(View.GONE);

        //listview头部
        mCustomAllHeadView = new CustomAllHeadView(getActivity());
        mListView.addHeaderView(mCustomAllHeadView);

        mListView.setPullLoadEnable(false);
        mListView.setPullRefreshEnable(true);
        mListView.setTransparentBg();
        mSidebar = (SideBar) findView().findViewById(R.id.layout_sideBar);
        mSidebar.setVisibility(View.GONE);
        mIndexFlagTv = (TextView) findView().findViewById(R.id.all_customer_indexflag_textView);
        mSidebar.setTextView(mIndexFlagTv);

        mAdapter = new CustomerAllAdapter(getActivity());
        mListView.setAdapter(mAdapter);

        emptyView = findView().findViewById(R.id.empty_view);
    }

    protected void initListener() {
        mListView.setXListViewListener(this);
        mAdapter.setOnActionClickListener(this);
        mSidebar.setOnTouchingLetterChangedListener(this);

        mCustomerSearchView.setOnClickListener(this);
    }

    protected void initData() {
        mPresenter = new CustomerAllPresenter(this);
    }

    @Override
    public void onRefresh() {
        mPresenter.refreshAll();
    }

    @Override
    public void onLoadMore() {

    }

    @Override
    public void setCustomers(List<Custom> customers) {
        mAdapter.setItems(customers);

        if (customers != null && customers.size() > 0) {
            updateIndexFlag(customers);
            mSidebar.setVisibility(View.VISIBLE);
            emptyView.setVisibility(View.GONE);
        } else {
            emptyView.setVisibility(View.VISIBLE);
            mSidebar.setVisibility(View.GONE);
        }
        setCustomCount();
    }

    /**
     * 更新右侧字母索引
     *
     * @param customers
     */
    private void updateIndexFlag(List<Custom> customers) {
        List<String> indexFlag = new ArrayList<>();
        String[] chars = new String[indexFlag.size()];
        mSidebar.setIndexChars(indexFlag.toArray(chars));
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);

        if (isVisibleToUser && mPresenter != null && mPresenter.isFirstRefreshFail()) {
            mPresenter.refreshCustoms();
        }
    }


    @Override
    public void updateTypeSucc(int type) {
        String msg = null;
        if (type == Custom.TYPE_UNSOLD_CUSTOMER) {
            msg = "已成功标为准客户";
        } else if (type == Custom.TYPE_SOLDED_CUSTOMER) {
            msg = "恭喜签单,已成功标记";
        } else {
            msg = "已取消";
        }
        ToastUtils.toastMessage(getActivity(), msg);
        mPresenter.refreshCustoms();
    }

    @Override
    public void setCustomCount() {
        mCustomAllHeadView.setCustomCount();
    }

    @Override
    public void setDrpCount(int count) {
        mCustomAllHeadView.setDrpCount(count);
    }

    @Override
    public void showToast(int resId) {
        ToastUtils.toastMessage(getActivity(), resId);
    }

    @Override
    public void smoothTop() {
        if (mListView != null) {
            mListView.smoothScrollToPosition(0);
            TaskExecutor.scheduleTaskOnUiThread(200, new Runnable() {
                @Override
                public void run() {
                    mListView.setSelection(0);
                }
            });
        }
    }

    @Override
    public void loading() {
        if (mLoadingView == null) {
            mLoadingView = View.inflate(getActivity(), R.layout.view_loading_state_layout, null);
        }
        mLoadingView.setVisibility(View.VISIBLE);
        mListView.setVisibility(View.GONE);
        mSidebar.setVisibility(View.GONE);

        RelativeLayout view = (RelativeLayout) mLoadingView.getParent();
        if (view != null) {
            view.removeView(mLoadingView);
        }
        mRootView.addView(mLoadingView, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
        mCustomerSearchView.setVisibility(View.GONE);
    }

    @Override
    public void loadSucc() {
        mRootView.removeView(mLoadingView);
        mLoadingView = null;
        mListView.setVisibility(View.VISIBLE);
        mCustomerSearchView.setVisibility(View.VISIBLE);
        mListView.stopRefresh();
        mListView.setRefreshTime(System.currentTimeMillis());
    }

    @Override
    public void loadFail() {
        mRootView.removeView(mLoadingView);
        mLoadingView = null;
        mListView.setVisibility(View.VISIBLE);
        mCustomerSearchView.setVisibility(View.VISIBLE);
        mListView.stopRefresh();
    }

    @Override
    public void onItemClick(Custom custom) {
        CustomArchivesActivity.launch(getActivity(), custom);
    }

    @Override
    public void onItemLongClick(Custom custom) {
        showFloatMenu(custom);
    }

    private void showFloatMenu(final Custom custom) {
        final CommMenuDialog dialog = new CommMenuDialog(getActivity());
        dialog.setMenu(createMenu(custom));
        dialog.setMenuItemLisener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                dialog.dismiss();
                switch (position) {
                    case 0:
                        setUnsoldType(custom, custom.type == Custom.TYPE_UNSOLD_CUSTOMER);
                        break;
                    case 1:
                        setSoldedType(custom, custom.type == Custom.TYPE_SOLDED_CUSTOMER);
                        break;
                }
            }
        });
        dialog.show();
    }

    /**
     * 点击改变准客户类型
     *
     * @param custom
     */
    @EventTrace({EventID.APP_CUSTOMER_INDEX_CUSTOMER_ONE_UNREADY, EventID.APP_CUSTOMER_INDEX_CUSTOMER_ONE_READY})
    private void setUnsoldType(Custom custom, @EventTraceSelector boolean unsoldCustom) {
        int type = unsoldCustom ? Custom.TYPE_NORMAL_CUSTOMER : Custom.TYPE_UNSOLD_CUSTOMER;
        CustomsManager.getInstance().updateCustomType(custom.customerId, type);
    }

    /**
     * 点击改变已签单类型
     *
     * @param custom
     */
    @EventTrace({EventID.APP_CUSTOMER_INDEX_CUSTOMER_ONE_UNPAID, EventID.APP_CUSTOMER_INDEX_CUSTOMER_ONE_PAID})
    private void setSoldedType(Custom custom, @EventTraceSelector boolean soldedPay) {
        int type = soldedPay ? Custom.TYPE_NORMAL_CUSTOMER : Custom.TYPE_SOLDED_CUSTOMER;
        CustomsManager.getInstance().updateCustomType(custom.customerId, type);
    }


    /**
     * 根据客户的类型生成不同的弹出菜单列表
     *
     * @param custom
     * @return
     */
    private List<String> createMenu(Custom custom) {
        ArrayList<String> menu = new ArrayList<String>();
        switch (custom.type) {
            case Custom.TYPE_UNSOLD_CUSTOMER:
                menu.add("取消准客户");
                menu.add("标为已签单");
                break;

            case Custom.TYPE_SOLDED_CUSTOMER:
                menu.add("标为准客户");
                menu.add("取消已签单");
                break;
            case Custom.TYPE_NORMAL_CUSTOMER:
                menu.add("标为准客户");
                menu.add("标为已签单");
                break;
        }
        return menu;
    }

    @Override
    public void onTouchingLetterChanged(String s) {

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.customer_header_search:
                searchCustomer();
                break;
        }
    }

    /* 搜索客户 */
    private void searchCustomer() {
        CustomSearchActivity.launch(getActivity(), false, 0);
    }

    @Override
    public void onResume() {
        super.onResume();
        if (getUserVisibleHint())
            onRefresh();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (mPresenter != null) {
            mPresenter.onDestroy();
            mPresenter = null;
        }
    }

}